//
//  XYReadChapterModel.swift
//  XYReadBook
//
//  Created by fox on 2017/10/7.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

typealias LoadCallback = (_ loadSuccess: Bool)->()

class XYReadChapterModel {
    var titleString = ""
    var bookID = ""
    var url = ""
    var fullText: String = ""
    var pageFrameRefs: [CTFrame] = []
    var pageHeights: [CGFloat] = []
    var pageRanges: [NSRange] = []


    func loadData(callBack: @escaping LoadCallback) {

        HTTPManager.requestModel(url: url, method: .get, parameters: nil, iscaChe: true) {[weak self] (resp:XYChapterTextModel?, error) in
            guard let resp = resp,resp.ok == true,error == nil else {
                callBack(false)
                return
                
            }
            self?.fullText = resp.chapter.body
            self?.prase(content: self?.fullText ?? "",rect: DZMReadConfigure.rect, attributes: DZMReadConfigure.shared().readAttribute())
            callBack(true)
        }
    }
}

extension XYReadChapterModel {

    func prase(content: String, rect: CGRect, attributes: [String: Any]) {

        var tmpFrameRefs = [CTFrame]()
        var tmpRanges   = [NSRange]()
        var tmpHeights = [CGFloat]()

        let attrString = NSMutableAttributedString(string: content, attributes: attributes)
        let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)

        var location: CFIndex = 0
        var length: CFIndex = 0

        repeat {
            //            //  方式1:
            var fitRange = CFRange(location: 0, length: 0)
            let size = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(location, content.characters.count - location), nil, rect.size, &fitRange)

            //  方式2:
            let path = CGPath(rect: CGRect.init(origin: .zero, size: size), transform: nil)
            let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(location, content.characters.count - location), path, nil)
            let range = CTFrameGetVisibleStringRange(frame)
            //  矩形框内两种方式获取的range一样, 方式2可能功能强大一些, path可以不是矩形
            //  print(fitRange.length == range.length && fitRange.location == range.location)

            tmpHeights.append(size.height)
            tmpFrameRefs.append(frame)

            length = range.length
            tmpRanges.append(NSMakeRange(location, length))
            location += length

        } while (location < content.characters.count)

        pageFrameRefs = tmpFrameRefs
        pageHeights = tmpHeights
        pageRanges = tmpRanges
    }
}
